package com.zg.system.auth;

import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.zg.common.cache.service.impl.RedisCacheServiceImpl;
import com.zg.common.core.R;
import com.zg.common.web.Req;
import com.zg.common.core.User;
import com.zg.common.core.dao.auth.AuthUser;
import com.zg.common.core.dao.auth.AuthUserDao;
import com.zg.system.auth.vo.BindPhoneVo;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;

/**
 * @author Zxb
 */
@RestController
@RequiredArgsConstructor
public class PhoneController {
    private final AuthUserDao userDao;
    private final RedisCacheServiceImpl redisService;

    @PostMapping("/user/phone/send")
    public R sendPhoneMsg(@RequestBody String phone) {
        if (StrUtil.isBlank(phone)) {
            return R.error("请设置手机号");
        }
        if (!PhoneUtil.isMobile(phone)) {
            return R.error("请设置正确的手机号");
        }
        String code = RandomUtil.randomString(8);
        User u = Req.getCurrUser();
        AuthUser user = userDao.getById(u.getId());
        String key = user.getUsername() + ":phone:code";
        redisService.addKey(key, code, 300L);
        return R.success(code);
    }

    @PostMapping("/user/phone/bind")
    public R bindPhone(@RequestBody @Valid BindPhoneVo bindPhoneVo) {
        User u = Req.getCurrUser();
        AuthUser user = userDao.getById(u.getId());
        String code = bindPhoneVo.getCode();
        String key = user.getUsername() + ":phone:code";
        String value = redisService.findValue(key);
        if (!code.equals(value)) {
            return R.error("验证码错误");
        }
        redisService.delKey(key);
        user.setPhone(bindPhoneVo.getPhone());
        userDao.updateById(user);
        return R.success();
    }
}
